package com.wxy.ej.flow.modules.excelOnline.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rt.easyjava.common.base.MyQueryWrapper;
import com.rt.easyjava.common.base.PageDto;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.base.UserDetailsDto;
import com.rt.easyjava.common.config.dozer.MyMapper;
import com.rt.easyjava.common.utils.others.DateTool;
import com.rt.easyjava.common.utils.others.DateUtils;
import com.rt.easyjava.common.utils.others.StringUtils;
import com.wxy.ej.flow.modules.excelOnline.bean.ExcelOnline;
import com.wxy.ej.flow.modules.excelOnline.bean.ExcelOnlineUserLink;
import com.wxy.ej.flow.modules.excelOnline.dto.ExcelOnlineDto;
import com.wxy.ej.flow.modules.excelOnline.dto.ExcelOnlineUserLinkDto;
import com.wxy.ej.flow.modules.excelOnline.facade.ExcelOnlineFileApi;
import com.wxy.ej.flow.modules.excelOnline.service.beanService.ExcelOnlineService;
import com.wxy.ej.flow.modules.excelOnline.service.beanService.ExcelOnlineUserLinkService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * BusinessService 接口: 对外提供业务代码服务
 * @author wuxiaoyong
 * @since 2022-05-14
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class ExcelOnlineBizService {
    @Autowired
    protected MyMapper mapper;
    @Autowired
    protected ExcelOnlineService excelOnlineService;
    @Autowired
    protected ExcelOnlineUserLinkService excelOnlineUserLinkService;
    @Resource
    protected ExcelOnlineFileApi excelOnlineFileApi;
    @Resource
    private HttpServletRequest request;



    // 创建新的excel
    public Result createExcel(ExcelOnlineDto excelOnlineDto) {
        //取登录用户
        String userDetailsJson = request.getParameter("userDetailsJson");

        Result result = excelOnlineService.create(excelOnlineDto);
        ExcelOnline excelOnline = (ExcelOnline)result.getObj();

        //绑定用户关系表
        ExcelOnlineUserLink userLink = new ExcelOnlineUserLink();
        userLink.setCreatorUpdatorInfo(userDetailsJson);
        userLink.setTtfExcelOnlineId(excelOnline.getId());
        userLink.setTmptAuthUserId(userLink.getCreatorId());
        excelOnlineUserLinkService.save(userLink);

        //nosql: create a excel file
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("fileId",""+excelOnline.getId());
        paramMap.put("name",excelOnline.getName());
        Result result1 = excelOnlineFileApi.create(paramMap);
        if (!result1.isSuccess()){
            throw new RuntimeException(result1.getContentOnly());
        }

        return result1;
    }


    // 绑定excel
    public Result bindExcelByExcelOnlineId(String excelOnlineId) {
        //取登录用户
        String userDetailsJson = request.getParameter("userDetailsJson");

        //查询数据是否存在
        Result result = excelOnlineService.selectById(excelOnlineId);
        if (!result.isSuccess()) {
            return result;
        }
        if (result.getObj()==null) {
            return Result.builder().fault("指定的ID数据不存在");
        }

        //绑定用户关系表
        ExcelOnlineUserLink userLink = new ExcelOnlineUserLink();
        userLink.setCreatorUpdatorInfo(userDetailsJson);
        userLink.setTtfExcelOnlineId(Long.parseLong(excelOnlineId));
        userLink.setTmptAuthUserId(userLink.getCreatorId());
        excelOnlineUserLinkService.save(userLink);

        return Result.builder();
    }

    // 删除：绑定excel
    public Result deleteLink(String excelOnlineId) {
        //取登录用户
        String userDetailsJson = request.getParameter("userDetailsJson");
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(userDetailsJson);

        //删除：绑定用户关系表
        ExcelOnlineUserLink userLink = new ExcelOnlineUserLink();
        userLink.setTtfExcelOnlineId(Long.parseLong(excelOnlineId));
        userLink.setTmptAuthUserId(Long.parseLong(userDetailsDto.getUserId()));
        QueryWrapper queryWrapper = new QueryWrapper(userLink);
        excelOnlineUserLinkService.remove(queryWrapper);

        return Result.builder();
    }


    /**
     * 备份数据
     * 会有多人同时更新一条记录情况，加同步控制
     * @param excelOnlineDto
     * @return
     */
    synchronized public Result backupData(ExcelOnlineDto excelOnlineDto) {
        //取登录用户
        UserDetailsDto userDetailsDto = UserDetailsDto.getUserDetailsDto(request.getParameter("userDetailsJson"));

        ExcelOnline excelOnline = excelOnlineService.getById(excelOnlineDto.getId());

        // update
        String hisDataJsonString = excelOnline.getHisData();
        if (StringUtils.isNull(hisDataJsonString)) {
            hisDataJsonString = "[]";
        }
        JSONArray hisJsonArray = JSONArray.parseArray(hisDataJsonString);
        JSONObject verJsonObj = new JSONObject();
        verJsonObj.put("id",excelOnline.getId()+"-"+ DateTool.getCurrentDatetimeStr("yyyyMMddHHmmssSSS"));
        verJsonObj.put("name",excelOnlineDto.getVersionName());
        verJsonObj.put("createTime",DateTool.getCurrentDatetimeStr());
        verJsonObj.put("creator",userDetailsDto.getUserName());
        hisJsonArray.add(0,verJsonObj);
        //
        excelOnline.setHisData(hisJsonArray.toJSONString());
        excelOnlineService.updateById(excelOnline);

        //nosql: create a excel file
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("pFileId",""+excelOnline.getId());
        paramMap.put("fileId",verJsonObj.getString("id"));
        paramMap.put("name",verJsonObj.getString("name"));
        Result result1 = excelOnlineFileApi.backupData(paramMap);
        if (!result1.isSuccess()){
            throw new RuntimeException(result1.getContentOnly());
        }

        return Result.builder();
    }

}
